package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDisableFailedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.sky.constant.MessageConstant.DISH_DISABLE_FAILED;

@Service
public class DishServiceImpl implements DishService {

    private static final Logger log = LoggerFactory.getLogger(DishServiceImpl.class);

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setMealDishMapper;
    /**
     * 新增菜品，用事务方式
     * @param dishDTO
     */
    @Transactional
    @Override
    @ApiOperation("新增菜品")
    public void save(DishDTO dishDTO) {
        log.info("增加菜品{}", dishDTO);
        //向菜品表插入一条数据
//        Dish dish = Dish.builder()
//                .name(dishDTO.getName())
//                .status(dishDTO.getStatus()).
//                description(dishDTO.getDescription()).
//                image(dishDTO.getImage()).
//                price(dishDTO.getPrice()).
//                categoryId(dishDTO.getCategoryId()).
//                build();
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(0);
        dishMapper.save(dish);

        //向口味表插入多条数据
        if(!dishDTO.getFlavors().isEmpty()){
            dishDTO.getFlavors().forEach(dishFlavor -> {
                log.info("菜品-{}新增口味：{}", dishDTO.getName(), dishFlavor.getName());
                dishFlavor.setDishId(dish.getId());
                dishFlavorMapper.save(dishFlavor);
            });
        }
    }

    @ApiOperation("菜品分页查询")
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @ApiOperation("菜品批量删除功能")
    @Override
    public void deleteDish(List<Long> ids) {
        //启用的菜品不能删除,被套餐关联的菜品不能删除
        int countOfStatus = dishMapper.countOfSelectStatusById(ids);
        int countOfSetmeal = setMealDishMapper.countOfSelectByDishId(ids);
        if(countOfStatus > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        } else if (countOfSetmeal > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        else {
            //删除菜品
            dishMapper.deleteDish(ids);
            //删除菜品相关的口味数据
            dishFlavorMapper.delete(ids);
        }

    }

    @ApiOperation("菜品启用停售更改")
    @Override
    public void updateDish(Dish dish) {
        //不能禁用套餐起售中的菜品
        if(setMealDishMapper.countOfStartSetmealByDishId(dish.getId()) > 0 && dish.getStatus() == 0){
            throw new DishDisableFailedException(DISH_DISABLE_FAILED);
        }
        dishMapper.update(dish);
    }

    @ApiOperation("根据菜品id获取菜品数据")
    @Override
    public DishVO selectDishById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.selectDishById(id);
        List<DishFlavor> dishFlavor = dishFlavorMapper.selectDishFlavorById(id);
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    @ApiOperation("修改菜品")
    @Override
    public void updateDishALL(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //向口味表修改多条数据，通过先删除后增加的方式
        List<Long> ids = new ArrayList<>();
        ids.add(dishDTO.getId());
        dishFlavorMapper.delete(ids);
        if(!dishDTO.getFlavors().isEmpty()){
            dishDTO.getFlavors().forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
                log.info("菜品-{}修改口味为：{}", dishDTO.getName(), dishFlavor.getName());
                dishFlavorMapper.save(dishFlavor);
            });
        }
    }

    @Override
    public Dish[] selectDishByCategoryId(Long id) {
        return dishMapper.selectDishByCategoryId(id);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectDishFlavorById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
